package com.jing.weibo.controller.user;

import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import weibo4j.http.AccessToken;
import weibo4j.model.User;
import weibo4j.model.WeiboException;
import weibo4j.org.json.JSONObject;

import com.jing.system.comm.BaseController;
import com.jing.system.comm.contants.WeiboCons;
import com.jing.system.comm.enums.FansAttentionType;
import com.jing.weibo.pojo.UserInfo;
import com.jing.weibo.service.user.UserInfoService;
import com.jing.weibo.ws.sina.SinaService;

/**
 * 用户登录的Controller
 * @author jing.yue
 * @version 2012/08/29 1.0.0
 */
@Controller
public class UserController extends BaseController {

	private static final Logger logger = Logger.getLogger(UserController.class);

	/*@Autowired
	private TaskManager taskManager;*/

	@Autowired
	private SinaService sinaService;

	@Autowired
	private UserInfoService userInfoService;

	/**
	 * 跳转到管理页
	 * @return
	 */
	@RequestMapping("/main")
	public String main(HttpServletRequest request, ModelMap modelMap) {
		// TODO Auto-generated method stub

		UserInfo userInfo = getSessionUser(request);
		try {
			//处理当前 用户是否关注了开发用户
			JSONObject jsonObject = sinaService.showFriendship(userInfo.getUsername(), WeiboCons.system_weiboId, userInfo.getToken());
			boolean following = jsonObject.getJSONObject("source").getBoolean("following");
			//登录用户是否关注了开发用户
			modelMap.put("following", following);
		} catch (WeiboException e) {
			logger.error(WeiboCons.getErrorMsg(e));
			return "redirect:index.jsp?errorCode=" + e.getErrorCode();
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "redirect:index.jsp?errorCode=error";
		}
		removeSession(request, FORCELOGIN);
		return "main";
	}

	@RequestMapping("/weiboMain")
	public String weiboLogin(HttpServletRequest request, ModelMap modelMap, String code) {
		// TODO Auto-generated method stub
		//logger.info("进入微博授权登录!");
		try {
			//获取授权
			AccessToken accessToken = sinaService.getAccessTokenByCode(code);

			//获取用户信息
			User user = sinaService.showUserById(accessToken.getUid(), accessToken.getAccessToken());

			UserInfo userInfo = new UserInfo();
			//设置用户名为UID
			userInfo.setUsername(user.getId());
			//设置为新浪微博
			userInfo.setType(0);
			//昵称
			userInfo.setNickname(user.getScreenName());
			//关注数
			userInfo.setAttentionnum(Integer.toString(user.getFriendsCount()));
			//粉丝数
			userInfo.setFansnum(Integer.toString(user.getFollowersCount()));
			//微博数
			userInfo.setWeibonum(Integer.toString(user.getStatusesCount()));
			//头像
			userInfo.setImg(user.getavatarLarge());
			//授权的token
			userInfo.setToken(accessToken.getAccessToken());
			//授权到期时间
			userInfo.setAccessendtime(DateUtils.addSeconds(Calendar.getInstance().getTime(), Integer.parseInt(accessToken.getExpireIn())));

			//判断本地数据库是否存在信息
			if(userInfoService.findByUserName(userInfo) != null) {
				//更新用户信息
				userInfoService.updateUserInfo(userInfo);
			} else {
				//保存用户信息
				userInfoService.saveUserInfo(userInfo);
			}

			//获取用户对象
			userInfo = userInfoService.findByUserName(userInfo);

			setSessionUser(request, userInfo);
			
			//删除我的关注信息
			updateSynchrologInfo(request, FansAttentionType.TYPE_ATTENTION);
			//删除我的粉丝信息
			updateSynchrologInfo(request, FansAttentionType.TYPE_FANS);

			/*//添加定时任务同步数据-我的关注
			String dateStr = DateUtil.dateToString(Calendar.getInstance().getTime(), DateUtil.FMT_DEFAULT);
			taskManager.addTask(dateStr.substring(0, 10), dateStr.substring(11, 13), dateStr.substring(14, 16), dateStr.substring(17, 19), userInfo.getUsername(), userInfo.getToken(), FansAttentionType.TYPE_ATTENTION);

			//添加定时任务同步数据-我的粉丝
			dateStr = DateUtil.dateToString(Calendar.getInstance().getTime(), DateUtil.FMT_DEFAULT);
			taskManager.addTask(dateStr.substring(0, 10), dateStr.substring(11, 13), dateStr.substring(14, 16), dateStr.substring(17, 19), userInfo.getUsername(), userInfo.getToken(), FansAttentionType.TYPE_FANS);*/

		} catch (WeiboException e) {
			logger.error(WeiboCons.getErrorMsg(e));
			return "redirect:index.jsp?errorCode=" + e.getErrorCode();
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "redirect:index.jsp?errorCode=error";
		}
		return "redirect:main.shtml";
		//return "main";
	}

	/**
	 * 退出
	 * @param request
	 * @return
	 */
	@RequestMapping("/exit")
	public String exit(HttpServletRequest request) {
		// TODO Auto-generated method stub
		//logger.info("进入退出!");
		try {
			UserInfo userInfo = getSessionUser(request);
			setSession(request, FORCELOGIN, "true");
			if(userInfo != null) {
				removeSessionUser(request);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "redirect:index.jsp";
	}

	/**
	 * 修改用户是否开启互粉
	 * @return
	 */
	@RequestMapping(value = "/user/json/isOpenMp")
	@ResponseBody
	public ModelMap isOpenMp(HttpServletRequest request, Integer isopenmp) {
		// TODO Auto-generated method stub
		logger.info("修改用户是否开启互粉");
		String result = null;
		String weiboMsg = null;
		UserInfo userInfo = getSessionUser(request);
		try {
			userInfo.setIsopenmp(isopenmp);
			userInfoService.updateUserInfoIsopenmp(userInfo);

			setSessionUser(request, userInfo);
			result = SUCCESS;
		} catch (WeiboException e) {
			logger.error(WeiboCons.getErrorMsg(e), e);
			result = ERROR_WEIBO;
			weiboMsg = WeiboCons.getErrorMsg(e);
		} catch (Exception e) {
			logger.error("修改用户是否开启互粉异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("result", result);
		modelMap.put("weiboMsg", weiboMsg);
		return modelMap;
	}
}